import BScroll from '@better-scroll/core';
import PullUp from '@better-scroll/pull-up';
import ObserveDOM from '@better-scroll/observe-dom';

import { ref, onMounted, onUnmounted } from 'vue';

BScroll.use(PullUp);
BScroll.use(ObserveDOM);
// requestData异步请求
export default function usePullUpLoad(requestData, preventPullUpload) {
  const scroll = ref(null);
  // 初始化BScroll需要一个容器
  const rootRef = ref(null);
  // 是否正在拉取标识
  const isPullUpLoad = ref(false);
  onMounted(() => {
    // BScroll实例化
    // 开启上拉加载pullUpLoad: true
    // 实时观测变化自动刷新observeDOM: true
    // 允许列表点击click: true
    const scrollVal = scroll.value = new BScroll(rootRef.value, {
      pullUpLoad: true,
      observeDOM: true,
      click: true
    });

    // 监听上拉加载事件
    scrollVal.on('pullingUp', pullingUpHandler);

    async function pullingUpHandler() {
      // better-scroll在数据未填充满一屏时会自动触发上拉加载事件
      // 执行首次加载或者主动执行上拉加载时不去触发事件
      if (preventPullUpload.value) {
        scrollVal.finishPullUp();
        return;
      }
      isPullUpLoad.value = true;
      await requestData();
      // 请求结束后执行
      scrollVal.finishPullUp();
      scrollVal.refresh();
      isPullUpLoad.value = false;
    }
  });
  onUnmounted(() => {
    scroll.value.destroy();
  });
  return {
    scroll,
    rootRef,
    isPullUpLoad
  };
}
